<?php
declare (strict_types=1);

namespace app\listener\notify;

use app\event\SupplierNotifySuccess;
use app\model\CouponOrder;
use think\facade\Log;

class CouponButtSuccess
{
    /**
     * 事件监听处理
     * @param SupplierNotifySuccess $event
     * @return mixed
     */
    public function handle($event)
    {
        $couponOrder = $event->couponOrder;
        if ($couponOrder->serv_type != PRODUCT_COUPON_SERV && $couponOrder->type != CouponOrder::TYPE_COUPON_SELF_EMPLOYED) {
            return true;
        }

        if ($couponOrder->status == CouponOrder::C_STATUS_RECHARGE_SUCCESS) {
            return true;
        }


        $couponOrder->status = CouponOrder::C_STATUS_RECHARGE_SUCCESS;
        $couponOrder->supplier_status = CouponOrder::SUPPLIER_STATUS_SUCCESS;

        //等待结算了
        $couponOrder->agent_settle_status = CouponOrder::C_AGENT_SETTLE_STATUS_WAIT;
        $couponOrder->settled_at = getSettleDate($couponOrder->pay_time);//下个月25号


        //完成时间
        $couponOrder->order_finish_at = date('Y-m-d H:i:s');


        //todo 如果供应商结算价降低
        if ( ($couponOrder->new_supplier_price != 0)  && ($couponOrder->new_supplier_price < $couponOrder->supplier_price)) {
            try {
                //1.修改和供应商的结算价----供应商的结算价要降低
                $couponOrder->supplier_price = $couponOrder->new_supplier_price;
                //2.代理商看到的成本价settle_price----不变
                //3.代理商的利润profit---不变
                //4.平台的利润需要修改
                $couponOrder->platform_profit = bcadd((string)$couponOrder->platform_profit, (string)bccomp((string)$couponOrder->supplier_price, (string)$couponOrder->new_supplier_price));
                Log::warning('权益商品降价下单成功', [
                    'id'                 => $couponOrder->id,
                    'order_id'           => $couponOrder->order_id,
                    'supplier_price'     => $couponOrder->supplier_price ,
                    'new_supplier_price' => $couponOrder->new_supplier_price
                ]);
            } catch (\Exception $e) {
                // $e->getMessage();
            }
        }
        $couponOrder->save();
    }


}
